<template>
  <div class="video-crop-container">
    <div class="video-container" ref="videoContainerRef">
      <div class="video-real-size" ref="videoWrapper">
        <video
          ref="videoPlayer"
          :src="videoUrl"
          @loadedmetadata="getVideoDimensions"
          class="video"
          :controls="false"
        ></video>
        
      </div>
    </div>
    <div class="crop-ratio-box">
      <div class="video-controls">
        <!-- 播放/暂停控制 -->
        <div class="control-btn" @click="togglePlay">
          <pause-circle-filled v-if="isPlaying" />
          <play-circle-filled v-else />
        </div>
        <!-- 进度条 -->
        <div class="progress-container" ref="progressContainer" @click="seek">
          <div
            ref="startBtnRef"
            class="trim-handle start-handle"
            :style="{ left: starBtntLeft }"
            @mousedown="startDrag"
          ></div>
        </div>
        <div class="time-display">
          <span class="ml-5">
            {{ formatTime(currentTime) }} /
            {{ formatTime(videoDuration) }}</span
          >
        </div>
      </div>
      <div class="flex justify-between w-full mt-10 py-10">
      <div>
        <span v-if="numUnitValue&&numConsumesValue&&nameValue" class="coast-tip">每{{numUnitValue}}消耗{{pointConsumesValue}}{{pointUnitValue}}{{ nameValue }}, 不足1{{numUnitValue}}按1{{numUnitValue}}计算</span>
      </div>
        <div>
          <a-button
            class="ml-5"
            type="primary"
            @click="startCrop"
            :loading="loading"
            >开始处理</a-button
          >
          <a-button class="ml-5" @click="cancelCrop">取消</a-button>
        </div>
      </div>
      <a-form class="w-full" :labelCol="{span:3}" >
        <a-form-item label="原视频语言" required>
          <div class="select-box">
            <a-select
              v-model:value="currentLanguage"
              show-search
              :bordered="false"
              placeholder="请选择原视频语言"
              style="width: 100%"
              :options="languageList.filter((item) => item.target)"
              :filter-option="filterOption"
            >
            </a-select>
          </div>
        </a-form-item>
        <a-form-item label="目标语言" required>
          <div class="select-box">
            <a-select
              v-model:value="currentTranslateLanguage"
              mode="multiple"
              :bordered="false"
              placeholder="请选择目标语言"
              style="width: 100%"
              :options="languageList"
              :filter-option="filterOption"
            >
            </a-select>
          </div>
        </a-form-item>
        <a-form-item label="翻译类型" required>
          <div class="select-box">
          <a-select
            v-model:value="translateType"
            :bordered="false"
            placeholder="请选择翻译类型"
            style="width: 100%"
            :options="translateTypeList"
            :filter-option="filterOption"
            ></a-select>
          </div>
        </a-form-item>
       
      </a-form>
      <a-form class="w-full">
        <a-form-item label="擦除原字幕" required>
          <a-switch
                v-model:checked="isErase"
              />
        </a-form-item>
      </a-form>
    </div>
    <div class="mask" v-if="loading">
      <div class="loading">
        <span>处理中...</span>
      </div>
    </div>
  </div>
</template>
<script setup>

import {

  PauseCircleFilled,
  PlayCircleFilled,
} from "@ant-design/icons-vue";
import { ref, reactive } from "vue";
import { getComputingPowerDetail,languageList as langList } from "../utils/index.js";


const props = defineProps({
  videoUrl: {
    type: String,
    default: "",
  },
  loading: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["cancelCrop", "startCrop"]);
// 获取视频的原始宽高
let videoPlayer = ref();

let videoCssWdith = ref(0);
let videoCssHeight = ref(0);
let videoContainerRef = ref();
let videoDuration = ref(0);
let numUnitValue = ref("");
let numConsumesValue = ref("");
let pointConsumesValue = ref("");
let nameValue = ref("");
let pointUnitValue = ref("");


let currentTime = ref(0);
let progressContainer = ref();
let starBtntLeft = ref("0%");
let languageList = langList;
let currentLanguage = ref("zh");
let currentTranslateLanguage = ref(['en']);
let isErase = ref(true);

let translateType = ref("extract_video_caption_translate_point");
let translateTypeList = ref([
  {
    label: "视频字幕翻译",
    value: "extract_video_caption_translate_point",
  },
  {
    label: "视频语音翻译",
    value: "extract_video_voice_translate_point",
  },
]);

// 新增响应式数据
const videoWrapper = ref(null);

let isPlaying = ref(false);
const crop_box_data = reactive({
  width: 0,
  height: 0,
  x: 0,
  y: 0,
});
// 格式化时间显示
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  seconds = Math.floor(seconds % 60);
  return `${minutes}:${seconds.toString().padStart(2, "0")}`;
};

// 计算最大公约数（GCD）的函数
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));

const startCrop = () => {
   emit("startCrop", { 
    business_type: translateType.value,
    source_language: currentLanguage.value,
    target_language: currentTranslateLanguage.value,
    is_erase_caption: isErase.value,
  });
};
const cancelCrop = () => {
  emit("cancelCrop");
};
const togglePlay = () => {
  if (videoPlayer.value.paused) {
    videoPlayer.value.play();
    isPlaying.value = true;
  } else {
    videoPlayer.value.pause();
    isPlaying.value = false;
  }
};
// 拖动处理
const onDrag = (event) => {
  if (!videoPlayer.value.paused) {
    videoPlayer.value.pause();
    isPlaying.value = false;
  }
  const rect = progressContainer.value.getBoundingClientRect();
  const offsetX = event.clientX - rect.left;
  const newTime = (offsetX / rect.width) * videoDuration.value;
  if (newTime < videoDuration.value && newTime > 0) {
    starBtntLeft.value = `${(offsetX / rect.width) * 100}%`;
    currentTime.value = newTime;
    videoPlayer.value.currentTime = currentTime.value; // 设置视频播放时间
  }
};
// 停止拖动
const stopDrag = () => {
  document.removeEventListener("mousemove", onDrag);
  document.removeEventListener("mouseup", stopDrag);
  videoPlayer.value.pause();
  isPlaying.value = false;
  // 处理拖动结到视频结尾时间小数点问题
  if (Math.floor(currentTime.value) === Math.floor(videoDuration.value)) {
    currentTime.value = videoDuration.value;
    videoPlayer.value.currentTime = currentTime.value;
  }
};
const startDrag = () => {
  document.addEventListener("mousemove", onDrag);
  document.addEventListener("mouseup", stopDrag);
};

function autoFitContainer(parentWidth, parentHeight, childWidth, childHeight) {
  // 边界检查
  if (parentWidth <= 0 || parentHeight <= 0) {
    throw new Error("Invalid container dimensions");
  }
  if (childWidth <= 0 || childHeight <= 0) {
    return { width: parentWidth, height: parentHeight }; // 返回最大尺寸
  }
  // 计算宽高比
  const containerRatio = parentWidth / parentHeight;
  const childRatio = childWidth / childHeight;
  // 根据宽高比关系动态选择缩放方向
  let targetWidth, targetHeight;

  if (childRatio > containerRatio) {
    // 水平方向填满，垂直居中
    targetWidth = parentWidth;
    targetHeight = parentWidth / childRatio;
  } else {
    // 垂直方向填满，水平居中
    targetHeight = parentHeight;
    targetWidth = parentHeight * childRatio;
  }
  // 返回整数尺寸
  return { width: Math.round(targetWidth), height: Math.round(targetHeight) };
}

const initCropBoxData = async (init = false) => {
  let parentWidth = videoContainerRef.value.offsetWidth;
  let parentHeight = videoContainerRef.value.offsetHeight;
  let videoRealWidth = videoPlayer.value.videoWidth;
  let videoRealHeight = videoPlayer.value.videoHeight;
  let { width: finalParentWidth, height: finalParentHeight } = autoFitContainer(
    parentWidth,
    parentHeight,
    videoRealWidth,
    videoRealHeight
  );
  videoCssWdith.value = finalParentWidth + "px";
  videoCssHeight.value = finalParentHeight + "px";
};

const getVideoDimensions = () => {
  initCropBoxData(true);
  videoDuration.value = videoPlayer.value.duration;
  videoPlayer.value.addEventListener("timeupdate", () => {
    currentTime.value = videoPlayer.value.currentTime;
    starBtntLeft.value = (currentTime.value / videoDuration.value) * 100 + "%";

    // 如果视频结束，播放结束
    if (currentTime.value >= videoDuration.value) {
      isPlaying.value = false;
      currentTime.value = videoDuration.value;
    }
  });
};

getComputingPowerDetail({key:'extract_video_caption_translate_point'}).then((res) => {
  if (res) {
    let {
      numberInfo:{unit:numUnit,consumes:numConsumes},
      pointInfo:{unit:pointUnit,consumes:pointConsumes,name}
    } = res; 
   
    numUnitValue.value = numUnit;
    numConsumesValue.value = numConsumes;
    pointConsumesValue.value = pointConsumes;
    nameValue.value = name;
    pointUnitValue.value = pointUnit;
  } 
})

</script>
<style lang="less" scoped>
.video-crop-container {
  position: relative;
}

.video-container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 100%;
  height: 450px;
  background-color: rgba(0, 0, 0, 0.5);
}

.video-real-size {
  position: relative;
  width: v-bind(videoCssWdith);
  height: v-bind(videoCssHeight);
}

.video {
  position: relative;
  width: 100%;
  object-fit: contain;
}

.crop-box {
  outline: 2px dashed #00ff00;
  position: absolute;
  cursor: move;
}

.crop-ratio-box {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.mask {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  font-size: 16px;
  color: #fff;
  inset: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  cursor: not-allowed;
  .loading {
    color: white;
    width: 120px;
    height: 120px;
    box-sizing: border-box;
    border-radius: 50%;
    border-top: 10px solid #e74c3c;
    position: relative;
    animation: a1 2s linear infinite;
  }
  .loading span {
    width: 120px;
    height: 120px;
    display: block;
    text-align: center;
    line-height: 120px;
    animation: a2 2s linear infinite;
  }
  .loading:before,
  .loading:after {
    content: "";
    width: 120px;
    height: 120px;
    position: absolute;
    left: 0;
    top: -10px;
    box-sizing: border-box;
    border-radius: 50%;
  }
  .loading:before {
    border-top: 10px solid lawngreen;
    transform: rotate(120deg);
  }
  .loading:after {
    border-top: 10px solid var(--ss-primary-color);
    transform: rotate(-120deg);
  }

  @keyframes a1 {
    to {
      transform: rotate(360deg);
    }
  }
  @keyframes a2 {
    to {
      transform: rotate(-360deg);
    }
  }
}
.video-controls {
  width: 100%;
  height: 50px;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.6));
  display: flex;
  align-items: center;
  padding: 0 20px;
  gap: 15px;
  box-sizing: border-box;
  // z-index: 999;
  // margin-top: 3px;

  .control-btn {
    cursor: pointer;
    color: #fff;
    font-size: 28px;
    padding: 5px;
    transition: opacity 0.3s;

    &:hover {
      opacity: 0.8;
    }
  }

  .progress-container {
    flex: 1;
    position: relative;
    height: 4px;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 2px;
    cursor: pointer;
    &::before {
      content: "";
      position: absolute;
      top: 0;
      // transform: translateX(-50%);
      width: v-bind(starBtntLeft);
      height: 100%;
      background: #fff;
      left: 0;
      z-index: 1;
    }
  }

  .trim-handle {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;

    top: 50%;
    transform: translate(-50%, -50%);
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #fff;
    &:hover {
      opacity: 0.8;
    }
    cursor: all-scroll;
    // &::after {
    //   content: '';
    //   position: absolute;
    //   transform: translateX(-50%);
    //   width: 4px;
    //   height: 4px;
    //   background: #00ff00;
    //   left: 50%;
    //   bottom: 0;

    // }
  }

  .time-display {
    color: #fff;
    font-size: 12px;
  }

  .volume-control {
    display: flex;
    align-items: center;
    gap: 8px;

    span {
      cursor: pointer;
    }

    .volume-slider {
      width: 80px;
      height: 3px;
      background: rgba(255, 255, 255, 0.3);
      appearance: none;

      &::-webkit-slider-thumb {
        appearance: none;
        width: 10px;
        height: 10px;
        background: #fff;
        border-radius: 50%;
      }
    }
  }
}
.select-box {
  position: relative;
  display: flex;
  flex-direction: column;
  border: 1px solid #eeeeee;
  border-radius: 5px;

  .select-tip {
    position: absolute;
    bottom: -25px;
    left: 0px;
    color: #999;
    font-size: 12px;
  }
}
.coast-tip{
  color: #666;
}
</style>
